﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Medianamik.Core.DAL.SQL
{
    public class SetClauseList : ISqlQueryPart, IEnumerable<SetClause> 
    {
        private List<SetClause> _setClauses = new List<SetClause>();
        
        public SetClauseList Set(Column pColumn, IExpression pExpression)
        {
            _setClauses.Add(new SetClause(pColumn, pExpression));
            return this;
        }

        public StringBuilder ToSQL()
        {
            var builder = new StringBuilder();
            if (_setClauses.Count == 0)
            {
                return builder;
            }

            var firstSet = _setClauses.First();
            builder.Append(firstSet.ToSQL() );

            foreach (var set in _setClauses.Skip(1))
            {
                builder.Append(set.ToSQL());
            }
            return builder;
        }

        public IEnumerator<SetClause> GetEnumerator()
        {
            return _setClauses.GetEnumerator();
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return _setClauses.GetEnumerator();
        }

    }
    public class SetClause : ISqlQueryPart
    {
        private readonly Column _column;
        private readonly IExpression _expression; 
        public SetClause(Column pColumn, IExpression pExpression)
        {
            _column = pColumn;
            _expression = pExpression;
        }
        
        #region ISqlQueryPart Members

        public StringBuilder ToSQL()
        {
            var builder = new StringBuilder();
            builder.AppendLine(" SET " + _column.Name + " = ")
                .Append(_expression.ToSQL());

            return builder;
        }

        #endregion
    }
}
